//
//  AppDelegate.m
//  maintain
//
//  Created by 郑想 on 15/10/9.
//  Copyright (c) 2015年 ewin. All rights reserved.
//

#import "AppDelegate.h"
#import "SDWebImageManager.h"
#import "UIWindow+Extension.h"
#import "WMHttpTool.h"
#import "YWCommonTool.h"
#import "NSDate+Additions.h"
#import "YWConst.h"
#import "YWMacro.h"

#import "YWDBTool.h"
#import "YWDownloadMetaDataManager.h"
#import "YWLoginTool.h"
#import "YWLoginTool.h"
#import "YWLoginViewController.h"

#import "YWMissionManager.h"
#import "YWNotifyManager.h"
#import "YWPushManager.h"
#import "YWEwinManager.h"

#import "YWTestViewController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>

#import <UMMobClick/MobClick.h>
#import "UMessage.h"
#import <UserNotifications/UserNotifications.h>
#import <Bugly/Bugly.h>

@interface AppDelegate () <WMHttpToolDelegete,UNUserNotificationCenterDelegate> {
    //NSString* _updateUrl;
    NSDate *lastDate;
}

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] init];
    
    ////友盟统计
    UMConfigInstance.appKey = umengAppkey;
    UMConfigInstance.channelId = @"App Store";
    [MobClick setAppVersion:XcodeAppVersion];
    [MobClick setCrashReportEnabled:NO];
    [MobClick startWithConfigure:UMConfigInstance];
    ////友盟推送
    [UMessage startWithAppkey:umengAppkey launchOptions:launchOptions httpsenable:YES];
    //注册推送，如果要使用category的自定义策略，可以参考demo中的代码。
    [UMessage registerForRemoteNotifications];
    //设置是否允许SDK当应用在前台运行收到Push时弹出Alert框（默认开启）
    [UMessage setAutoAlert:NO];
    [UMessage setLogEnabled:NO];;
    
    //Bugly
    [Bugly startWithAppId:BuglyAppId];
    
    //注册推送(上面友盟已经注册了，这里不需要再注册)
    //因为在iOS10上设置－>通知里面没有易维保，这里再注册一次(友盟个垃圾,sdk都不去更新兼容iOS10)
    if (iOS10) {
        [[YWPushManager shareManager] registerRemoteNotification];
    }
    
    ///地图定位
    [AMapServices sharedServices].enableHTTPS = YES;
    [AMapServices sharedServices].crashReportEnabled = NO;
    [AMapServices sharedServices].apiKey = AMapAPIKey;

    self.window.frame = [UIScreen mainScreen].bounds;
    
    [self showRootViewController];

    [self.window makeKeyAndVisible];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleLogoutNoti:) name:KPushLogOutNotification object:nil];
    //全局配置
    //ExclusiveTouch的作用是可以达到同一界面上多个控件接受事件时的排他性,从而避免一些问题。也就是说避免在一个界面上同时点击多个button
    //[[UIButton appearance] setExclusiveTouch:YES];//这个好像没用
    [[UIView appearance] setExclusiveTouch:YES];
    return YES;
}

//- (void)applicationWillResignActive:(UIApplication*)application
//{
//}

- (void)applicationDidEnterBackground:(UIApplication*)application
{
    [WMHttpTool shareHttpTool].delegate = nil;
    [[WMHttpTool shareHttpTool] stopMonitoring];
}

//- (void)applicationWillEnterForeground:(UIApplication*)application
//{
//}

- (void)applicationDidBecomeActive:(UIApplication*)application
{
    [WMHttpTool shareHttpTool].delegate = self;
    [[WMHttpTool shareHttpTool] startMonitoring];
    
    //延时是为了[[WMHttpTool shareHttpTool] existenceNetwork]能检测到网络
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSDate *currentDate = [NSDate date];
        NSInteger minutes = [currentDate minutesAfterDate:lastDate];
        if (lastDate == nil || (lastDate && minutes >= 2)) {
            BOOL isLogin = [YWLoginTool isLogin];
            if (isLogin) {
                if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
                    lastDate = currentDate;
                    //各个模块的未读数和总数
                    [[YWEwinManager shareManager] selectIsExistNewMissionsUnReadCount];
                    //获取用户身份信息,更新同步任务的数据(去掉删除的任务)
                    [[YWEwinManager shareManager] requestDatas];
                }else{
                    YWLog(@"applicationDidBecomeActive:无网络");
                }
            }else{
                YWLog(@"applicationDidBecomeActive:未登录");
            }
        }
    });
}

- (void)applicationWillTerminate:(UIApplication*)application
{
    YWLog(@"%p", __func__);
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application
{
    SDWebImageManager* mgr = [SDWebImageManager sharedManager];
    [mgr cancelAll];
    [mgr.imageCache clearMemory];
}

#pragma mark - push Methods
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    YWLog(@"didFailToRegisterForRemoteNotificationsWithError:%@",error);
}

- (void)application:(UIApplication*)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
    NSString* tokenTmp = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    NSString* token = [tokenTmp stringByReplacingOccurrencesOfString:@" " withString:@""];
    YWLog(@"注册成功,deviceToken:%@", token);
    //1.2.7版本开始不需要用户再手动注册devicetoken，SDK会自动注册
    //[UMessage registerDeviceToken:deviceToken];
    
    [YWPushManager shareManager].deviceToken = token;
    if ([YWLoginTool isLogin]) {
        [[YWEwinManager shareManager] uploadDeviceInfoWithDeviceToken:token IsLogin:0 WithComplete:^(NSInteger statusCode) {
            //已有设备登录，需要下线重新登录
            if (statusCode==406) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self appNeedLogout];
                    [self showLogoutAlert];
                });
            }
        }];
    }
}

#pragma mark - iOS8以上10以下系统的通知回调
- (void)application:(UIApplication*)application
    didReceiveRemoteNotification:(NSDictionary*)userInfo
          fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    YWLog(@"didReceiveRemoteNotification PUSH NOTI:%@", userInfo);
    [self handleReceiveRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - iOS10系统的通知回调
//在前台收到通知的时候回调
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    YWLog(@"iOS10 willPresentNotification PUSH NOTI:%@", userInfo);
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        [self handleReceiveRemoteNotification:userInfo];
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    //completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//在后台收到通知的时候回调
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    YWLog(@"iOS10 didReceiveNotificationResponse PUSH NOTI:%@", userInfo);
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        [self handleReceiveRemoteNotification:userInfo];
    }else{
        //应用处于后台时的本地推送接受
    }
}

- (void)handleReceiveRemoteNotification:(NSDictionary*)userInfo{
    [UMessage didReceiveRemoteNotification:userInfo];
    [[YWPushManager shareManager] handleRemoteNoti:userInfo];
}

#pragma mark - Init AVOS
///- (void)initAvosWithOptions:(NSDictionary*)launchOptions
//{
    ///使用友盟的统计
//    [AVOSCloudCrashReporting enable];
 //   [AVOSCloud setApplicationId:kAVOSAppID clientKey:kAVOSAppKey];
    //  [AVOSCloud setAllLogsEnabled:YES];
  //  [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
//}

- (void)showRootViewController
{
    BOOL isLogin = [YWLoginTool isLogin];
    if (isLogin) { // 之前已经登录成功过
        [[YWDBTool shareDBTool] connectDB:[YWLoginTool DBName]];
        YWLog(@"DB path: %@", [[YWDBTool shareDBTool] dbPath]);

        [[YWDownloadMetaDataManager shareManager] serialDownloadDatasWithComplete:nil];
        [self.window switchRootViewController];
    }else {
        self.window.rootViewController = [[YWLoginViewController alloc] init];
    }
}

#pragma mark - WMHttpToolDelegete
- (void)reachabilityStatusChange:(BOOL)existNetwork
{
    BOOL isLogin = [YWLoginTool isLogin];
    if (isLogin) {
        YWLog(@"判断网络状态的变化,上传失败的记录,状态:%@",existNetwork?@"有网络":@"无网络");
        [[YWEwinManager shareManager] netWorkStatusChange:existNetwork];
    }else {
        YWLog(@"未登录,暂不可上传");
    }
    
}

-(void)handleLogoutNoti:(NSNotification*)noti{
    //退出登录
    [self appNeedLogout];
    //显示alertVew
    NSDictionary* userInfo = noti.userInfo;
    NSData* data = [[userInfo objectForKey:@"content"] dataUsingEncoding:NSUTF8StringEncoding];
    NSError* error;
    NSDictionary *contentDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves  error:&error];
    
    NSTimeInterval exitTime  = [[contentDic objectForKey:@"exitTime"] longLongValue];
    NSString* deviceName = [contentDic objectForKey:@"deviceInfo"];
    [self showLogOutAlertViewWithExitTime:exitTime deviceName:deviceName];
}

- (void)appNeedLogout{
    [YWLoginTool saveLoginofStatus:NO];
    
    [[WMHttpTool shareHttpTool] cancelAllRequest];
    [[YWDBTool shareDBTool] closeDatabase];
    
    [[YWPushManager shareManager] removeAllUMengAliasAndTags];
    NSString* token = [[YWPushManager shareManager] deviceToken];
    [[YWEwinManager shareManager] requestLogoutWithDeviceToken:token WithComplete:nil];
    
    self.window.rootViewController = [[YWLoginViewController alloc] init];
}

- (void)showLogOutAlertViewWithExitTime:(NSTimeInterval)exitTime deviceName:(NSString*)deviceName{
    NSString* time = [YWCommonTool recordDateByFormatTimeString:exitTime/1000 showYear:YES];
    NSString* content = [NSString stringWithFormat:@"您的帐号已于 %@ 在另一台设备 %@ 登录,如果这不是你的操作,请尽快修改密码,并重新登录",time,deviceName];
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:content message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
}

- (void)showLogoutAlert{
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"您的账号已经在另一台设备登录,您需要重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
}

//- (void)version
//{
//    [[WMHttpTool shareHttpTool] getWithUrl:kAppUpgradeCheckUrl
//        params:nil
//        success:^(NSHTTPURLResponse* response, id json) {
//            if ([json isKindOfClass:[NSDictionary class]]) {
//                NSDictionary* appVersionJson = json;
//
//                _updateUrl = [appVersionJson objectForKey:@"update_url"];
//                NSString* currentVersion = [appVersionJson objectForKey:@"version"];
//
//                NSString* localVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
//
//                NSString* newVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
//                NSString* newlocalVersion = [localVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
//
//                NSString* msg = [NSString stringWithFormat:@"你当前的版本是V%@，发现新版本V%@，是否下载新版本？", localVersion, currentVersion];
//                if ([newVersion integerValue] > [newlocalVersion intValue]) {
//                    UIAlertView* createUserResponseAlert = [[UIAlertView alloc] initWithTitle:@"升级提示!" message:msg delegate:self cancelButtonTitle:@"下次再说" otherButtonTitles:@"现在升级", nil];
//                    [createUserResponseAlert show];
//                }
//            }
//        }
//        failure:^(NSHTTPURLResponse* response, NSError* error) {
//            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
//        }];
//}

//- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (buttonIndex == 1) {
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_updateUrl]];
//    }
//}

@end
